#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int appear(char*s1,char*s2);
int main()
{
    char line[256];
    int if_num=0, while_num, for_num=0;
    char string1[3] = "if";
    char string2[6] = "while";
    char string3[4] = "for";

    //将文件中的数据读入到字符数组中
    FILE *fp = fopen("test.c","r");  //以输入的方式打开文件
    if(fp==NULL)       //测试是否成功打开
    {
        printf("source code read error!\n");
        exit(1);
    }
    while(!feof(fp))
    {
        fgets(line,256, fp);  //读入一行
        if_num+=appear(line, string1);
        while_num+=appear(line, string2);
        for_num+=appear(line, string3);
    }
    fclose(fp);
    //识别结论
    printf("if: %d\n", if_num);
    printf("while: %d\n", while_num);
    printf("for: %d\n", for_num);
    return 0;
}

//返回s2在s1中出现了几次
int appear(char*s1,char*s2)
{
    int n=0,flag;
    char *p,*q;
    for(; *s1!='\0'; s1++)
    {
        if (*s2==*s1) /*判断字符串中是否有和要判断的字串首字符相同的字符*/
        {
            flag=1;
            p=s1 ; /*s1 p 为第一个相同字符的地址*/
            q=s2;
            for(; *q!='\0';) /*如果有则判断接下去的几个字符是否相同*/
            {
                if (*q++!=*p++)
                {
                    flag=0;
                    break;
                }
            }
            if (flag==1) n++;
        }
    }
    return(n);
}